<?php
/**
 * Created by PhpStorm.
 * User: 86182
 * Date: 2020/6/26
 * Time: 13:31
 */

namespace App\Serves;
use App\Models\Order\Order;
use App\Models\Order\OrderGoods;
use App\Serves\CartServe;

use App\Models\Goods\Goods;
use App\Models\Goods\GoodsSku;
use App\Utils\Show;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Jobs\DelayOrder;


class OrderServe
{

    public static function saveOrder($ids, $user_id){
        //订单号
        $order_id = date('YmdHis',time()).mt_rand(10000,99999).$user_id;
        $res =  CartServe::allCarts($user_id, $ids);

        $res_new = array_map(function ($v) use($order_id){
            $v['sku_id'] = $v['id'];
            $v['order_id'] = $order_id;
            unset($v['id']);
            unset($v['create_time']);
            return $v;
        }, $res);
//var_dump($res);exit;
        $data = [
            'user_id'=>$user_id,
            'order_id'=>$order_id,
            'price_all'=>array_sum( array_column($res, 'all_price')),
            'address_id'=>12,

        ];

        DB::beginTransaction();

        try{
//        主表新增 order 返回id

//            $res_order = (new Order())->saveOrder($data);
            $res_order = Order::insertGetId($data);

//            var_dump($res_order);
//        附表 order_goods

//         更新goods_sku
            GoodsSkuServe::updateNum($res_new);
//         更新goods
//         删除购物车里面的商品
            $ids = explode(',', $ids);
            CartServe::del($ids, $user_id );
//var_dump($res_order);
            (new DelayOrder())::dispatch(['id'=>$res_order])->delay(now()->addMinutes(1))->onQueue('clickQueue');

            DB::commit();

        }catch ( \Exception $e){
            DB::rollBack();

        }
        return $res_order;
    }

    public static function getGoodsById($id){
        if($id){
            $goods = Order::getOrderById($id);
            if($goods) return $goods??[];
        }
        return [];
    }


}